package com.ypz.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ypz.reggie.common.MyBaseContext;
import com.ypz.reggie.common.R;
import com.ypz.reggie.entity.Orders;
import com.ypz.reggie.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    //JSON数据要加注解
    public R<String> submit(@RequestBody Orders orders){

        ordersService.submit(orders);

        return R.success("下单成功");

    }

    /**
     * 后台查询订单
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime){

        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.like(number != null, Orders::getNumber , number);
        //还要个查询时间范围，TODO

        ordersService.page(ordersPage,lqw);

        return R.success(ordersPage);
    }

    /**
     * 修改订单状态，派送订单
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> modifyStatus(@RequestBody Orders orders){

        boolean b = ordersService.updateById(orders);
        if (b){
            return R.success("已派送");
        }
        return R.error("未知错误");

    }

    /**
     * 移动端订单分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> userPage(int page, int pageSize){
        Page<Orders> ordersPage = new Page<>(page, pageSize);

        Long userId = MyBaseContext.getCurrentId();

        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.eq(userId != null, Orders::getUserId, userId);

        ordersService.page(ordersPage, lqw);

        return R.success(ordersPage);
    }

}